package se.topshelf.golftracker.core.domain;


import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * User: magnusalmeby
 * Date: 2011-04-03
 */
@Entity
@Table(name="MemberClub")
public class MemberClub extends BaseEntity implements Comparable<MemberClub>{
    @NotNull
    private String name;

    @Embedded
    private Address address;

    @OneToMany(mappedBy = "memberClub")
    @Sort(type = SortType.NATURAL)
    private SortedSet<Player> members = new TreeSet<Player>();

    @OneToMany(mappedBy = "memberClub")
    @Sort(type = SortType.NATURAL)
    private SortedSet<Course> courses = new TreeSet<Course>();

    public MemberClub() {
    }

    public MemberClub(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public SortedSet<Player> getMembers() {
        return members;
    }

    public void addMember(Player player){
        assertNotAlreadyAdded(player, members);
        player.setMemberClub(this);
        members.add(player);
    }

    void setMembers(SortedSet<Player> members) {
        this.members = members;
    }

    public SortedSet<Course> getCourses() {
        return courses;
    }

    public void addCourse(Course course){
        course.setMemberClub(this);
        assertNotAlreadyAdded(course, courses);
        courses.add(course);
    }

    public void removeCourse(Course course){
        courses.remove(course);
        course.setMemberClub(null);
    }


    public void setCourses(SortedSet<Course> courses) {
        this.courses = courses;
    }

    @Override
    public String getGuiDescription() {
        return name;
    }

    public int compareTo(MemberClub o) {
        return name.compareTo(o.getName());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MemberClub that = (MemberClub) o;

        if (!name.equals(that.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("MemberClub");
        sb.append("{name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
